home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / std / c++ / 559 / text0000.txt < prev   
Encoding:
Text File  |  1996-08-06  |  2.2 KB  |  60 lines

  1. In article <4gsi2p$905@bcarh8ab.bnr.ca>,
  2. brian (b.c.) white <bcwhite@bnr.ca> wrote:
  3. >In article <pgpmoose.199602221531.14635@isolde.mti.sgi.com>,
  4. >ian (i.) willmott <willmott@bnr.ca> wrote:
  5. >
  6. >>In an article entitled "Q: Generic Callbacks -- Object->*func(...)"
  7. >>(reference <4fti32$p3p@bcarh8ab.bnr.ca>), bcwhite@bnr.ca asks
  8. >
  9. >>"Does the C++ standard allow for a generic callback to be specified?
  10. >>Basically, I'd like to be able to pass an arbitrary object and
  11. >>function of that object to be called at some later time."
  12. >
  13. >>What is needed is the ability to use member functions as callbacks
  14. >>without any constraint on the type of the object they are invoked on.
  15. >>This is possible in C++ only by using various implementation-dependent
  16. >>hacks to escape the type system, because the language does not provide
  17. >>any way to express such a construct.
  18. >
  19. >Of course, what we're really trying to with all this is to pass _code_
  20. >(along with its context) as an object.
  21.  
  22. There exist a rather simple solution using a static member function. 
  23. Instead of having the callback call a normal member function it can 
  24. call a static callback member function with the object as a 
  25. argument. Then this callback function can call the real callback function.
  26. This will involve an extra callback function for each callback one has,
  27. but on the other hand it involves no changes to the base class if
  28. one want to override the real callback function in a derived class.
  29.  
  30. class X
  31. {
  32. public:
  33.   static void callback(void* to)
  34.   virtual void real_callback();
  35. };
  36.  
  37. void X::callback(void* to)
  38.   X* me = (X*)to;
  39.   me ->real_callback()
  40. }
  41.  
  42. Motif widget callbacks and event handlers are examples where this pattern
  43. works without problems. 
  44.  
  45. If the desired class Y can not be modified it is possible that X is a helper
  46. class that knows which member function on the real class Y it shall call.
  47. I.e. this solution is portable and can be used for all possible classes.
  48.  
  49. Anders
  50.  
  51.  
  52.  
  53. [ comp.std.c++ is moderated.  To submit articles: Try just posting with your
  54.                 newsreader.  If that fails, use mailto:std-c++@ncar.ucar.edu
  55.   comp.std.c++ FAQ: http://reality.sgi.com/austern/std-c++/faq.html
  56.   Moderation policy: http://reality.sgi.com/austern/std-c++/policy.html
  57.   Comments? mailto:std-c++-request@ncar.ucar.edu
  58. ]
  59.